(function($) {
    function _ScrollAnimater(target, duration) {
        target = target || 0;
        if(Type.isNumber(target)){
            this.position = {
                left : 0,
                top : target
            };
        } else {
            if(!(target instanceof Element)){             
                target = document.getElementById(target);             
            }   
            this.position = $(target).getPosition();
        }
        this.duration = duration || 500;
        this.scroll = $.getScroll();
    }

    _ScrollAnimater.prototype.start = function() {
        var _this = this;
        _this.startTime = Date.tick();
        _this.timer = window.setInterval(function() {
            _this.step();
        }, 13);
    };
    
    _ScrollAnimater.prototype.step = function() {
        var _this = this;
        var tick = Date.tick();
        var p = (tick - _this.startTime) / _this.duration;
        if (tick >= _this.duration + _this.startTime) {
            this.stop();
            (function() {
                window.scrollTo(_this.position.left, _this.position.top);
            }).defer(13);
        } else {
            window.scrollTo(((-Math.cos(p * Math.PI) / 2) + 0.5) * (_this.position.left - _this.scroll.left) + _this.scroll.left, ((-Math.cos(p * Math.PI) / 2) + 0.5) * (_this.position.top - _this.scroll.top) + _this.scroll.top);
        }
    };
    
    _ScrollAnimater.prototype.stop = function() {
        if (this.timer) {
            window.clearInterval(this.timer);
            this.timer = null;
        }
    };
    
    //-----------------------------------------------------------------------------------------------------

    ujs.define('scrollAnimater', 'ujs.browser', {
        /**
         * 
         * @param {Element|Number} target
         */
        scrollTo : function(target) {
            (new _ScrollAnimater(target)).start();
        }
    });    
})($); 